package insight.app.config;


import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@Configuration
@Import({DAOConfig.class, ControllerConfig.class})
@ComponentScan
@PropertySource("classpath:dao.properties")
public class RootConfiguration {
	@Autowired
	private Environment environment;
	
	@Bean
	public DataSource dataSource() {
		System.out.println("instantiating datasource");
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(environment.getProperty("db.driver"));
		dataSource.setUrl(environment.getProperty("db.url"));
		dataSource.setUsername(environment.getProperty("db.user"));
		dataSource.setPassword(environment.getProperty("db.password"));
		
		return dataSource;
	}
	
	@Bean
	public JdbcTemplate jdbcTemplate(){
		System.out.println("instantiating  template");
		JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource());
		return jdbcTemplate;
	}
	
	@Bean
	public JavaMailSenderImpl javaMailSenderImpl(){
		System.out.println("instantiating  mailSender");
		JavaMailSenderImpl javaMailSenderImpl=new JavaMailSenderImpl();
		javaMailSenderImpl.setHost(environment.getProperty("mail.host"));
		javaMailSenderImpl.setPort(Integer.parseInt(environment.getProperty("mail.port")));
		javaMailSenderImpl.setUsername(environment.getProperty("mail.username"));
		javaMailSenderImpl.setPassword(environment.getProperty("mail.password")); 
		Properties javaMailProperties=new Properties();
		javaMailProperties.setProperty(environment.getProperty("mail.auth"),environment.getProperty("mail.auth.value"));
		javaMailProperties.setProperty(environment.getProperty("mail.ttls"),environment.getProperty("mail.ttls.value"));
		javaMailProperties.setProperty(environment.getProperty("mail.trust"),environment.getProperty("mail.trust.value"));
		javaMailProperties.setProperty(environment.getProperty("mail.debug"),environment.getProperty("mail.debug.value"));
		javaMailSenderImpl.setJavaMailProperties(javaMailProperties);
		return javaMailSenderImpl;
	}
}
